#include <iostream>
#include <cstdio>
#include <string>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>


//设置fd为非阻塞状态
void SetFd(int fd)
{
    int n = fcntl(fd,F_GETFL);

    if(n < 0)
    {
        perror("fcntl :");
        return;
    }

    fcntl(fd,F_SETFL,n | O_NONBLOCK);
}


int main()
{
    //设置输入流为非阻塞状态
    SetFd(0);

    std::string tips = "Please Enter# ";
    char buff[1024];
    while(1)
    {
        //输出到屏幕
        write(1, tips.c_str(), tips.size());
        //读取
        int n = read(0,buff,sizeof(buff));
        if(n > 0)
        {
            buff[n] = 0;
            std::cout<<"buff : "<<buff<<std::endl;
        }
        else if(n = 0)
        {
            std::cout<<"file end" << std::endl;
        }
        else
        {
            // EAGAIN		11	/* Try again */ - 被信号中断了 重读
            // EWOULDBLOCK	EAGAIN	/* Operation would block */ -- 没有数据可读
            if(errno == EWOULDBLOCK || errno == EAGAIN)
            {
                std::cout<<"没有数据可读"<<std::endl;
            }
            else if(errno == EAGAIN)
            {
                std::cout<<"被信号中断了"<<std::endl; 
            }
            else
            {
                std::cout<<"发生错误"<<std::endl;
                return -1;
            }
        }

        sleep(1);

    }

    return 0;
}